"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 基础功能
Case Name   : 数据传输过程中切换发布方式
Create At   : 2022/3/5
Owner       : opentestcase026
Description :
    1.在两个集群创建表
    2.创建发布端
    3.创建订阅指定二进制模式
    4.发布端插入数据
    5.发布端插入数据的同时，订阅端修改发布模式为非二进制模式
    6.订阅端查询表数据
    7.更新发布端数据
    8.发布端修改数据的同时，订阅端修改发布模式为二进制模式
    9.订阅端查询表数据
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.成功
    6.数据同步
    7.成功
    8.成功
    9.数据同步
History     :
    Modified by opentestcase001 2022/5/24:修改传输方式会造成发布订阅重连，有5s中断，
    修改脚本增加等待
    Modified by opentestcase004 2022/8/04:增加基础数据同步功能后订阅端有基础数据的同
    时再在订阅端修改表数据，主键冲突，关闭基础数据同步
"""
import unittest
import os
from yat.test import macro
from yat.test import Node
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != Primary_SH.get_node_num(), '非1+2环境不执行')
class Pubsubclass(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info("-----------this is setup-----------")
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.pri_userdb_pub = Node(node='PrimaryDbUser')
        self.pri_userdb_sub = Node(node='remote1_PrimaryDbUser')
        self.constant = Constant()
        self.commsh_pub = CommonSH('PrimaryDbUser')
        self.commsh_sub = CommonSH('remote1_PrimaryDbUser')
        self.com_pub = Common()
        self.tb_name = 'tb_pubsub_case190'
        self.mv_name1 = 'mv_pubsub_case190_1'
        self.mv_name2 = 'mv_pubsub_case190_2'
        self.subname = "sub_case190"
        self.pubname = "pub_case190"
        self.port = str(int(self.pri_userdb_pub.db_port) + 1)
        self.wal_level = self.com_pub.show_param("wal_level")
        self.user_param_pub = f'-U {self.pri_userdb_pub.db_user} ' \
            f'-W {self.pri_userdb_pub.db_password}'
        self.user_param_sub = f'-U {self.pri_userdb_sub.db_user} ' \
            f'-W {self.pri_userdb_sub.db_password}'
        self.value = 1000

    def test_pubsub(self):
        text = '--step:预置条件,修改pg_hba expect:成功'
        self.log.info(text)
        guc_res = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host    replication  {self.pri_userdb_sub.db_user} '
            f'{self.pri_userdb_sub.db_host}/32 sha256')
        self.log.info(guc_res)
        self.assertTrue(guc_res, '执行失败:' + text)
        if 'logical' != self.wal_level:
            result = self.commsh_pub.execute_gsguc(
                'set', self.constant.GSGUC_SUCCESS_MSG, 'wal_level=logical')
            self.assertTrue(result, '执行失败:' + text)
            result = self.commsh_pub.restart_db_cluster(True)
            flg = self.constant.START_SUCCESS_MSG in result \
                  or 'Degrade' in result
            self.assertTrue(flg, '执行失败:' + text)
        guc_res = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host    replication  {self.pri_userdb_pub.db_user} '
            f'{self.pri_userdb_pub.db_host}/32 sha256',
            macro.DB_ENV_PATH_REMOTE1)
        self.log.info(guc_res)
        self.assertTrue(guc_res, '执行失败:' + text)

        text1 = '--step1:两个集群均创建表 expect:成功--'
        self.log.info(text1)
        sql_create = f"create table {self.tb_name}(i int primary key, j int);"
        result = self.commsh_pub.execut_db_sql(sql_create,
                                               self.user_param_pub)
        self.log.info(result)
        self.assertEqual(result.count(self.constant.CREATE_TABLE_SUCCESS),
                         2, '执行失败:' + text1)
        result = self.commsh_sub.execut_db_sql(sql_create,
                                               self.user_param_sub,
                                               None,
                                               macro.DB_ENV_PATH_REMOTE1)
        self.log.info(result)
        self.assertEqual(result.count(self.constant.CREATE_TABLE_SUCCESS),
                         2, '执行失败:' + text1)

        text = '--step2:创建发布端 expect:成功--'
        self.log.info(text)        
        sql = f"CREATE PUBLICATION {self.pubname} FOR ALL TABLES;"
        result = self.commsh_pub.execut_db_sql(sql, 
                                               self.user_param_pub)
        self.log.info(result)
        self.assertIn(self.constant.create_pub_succ_msg, result,
                      '执行失败:' + text)
        self.assertNotIn(self.constant.SQL_WRONG_MSG[1], result,
                         '执行失败:' + text)

        text = '--step3:创建订阅 expect:成功--'
        self.log.info(text)
        result = self.commsh_sub.execute_generate(
            macro.COMMON_PASSWD, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.assertIn(self.constant.create_keycipher_success,
                      result, '执行失败:' + text)
        sql = f"CREATE SUBSCRIPTION {self.subname} CONNECTION " \
            f"'host={self.pri_userdb_pub.db_host} " \
            f"port={self.port} " \
            f"user={self.pri_userdb_pub.db_user} " \
            f"dbname={self.pri_userdb_pub.db_name} " \
            f"password={self.pri_userdb_pub.ssh_password}' " \
            f"PUBLICATION {self.pubname} with (binary=True, copy_data=false);"
        result = self.commsh_sub.execut_db_sql(sql, self.user_param_sub, None,
                                               macro.DB_ENV_PATH_REMOTE1)
        self.log.info(result)
        self.assertIn(self.constant.create_sub_succ_msg,
                      result, '执行失败:' + text)

        text = '--step4:发布端插入数据 expect:成功--'
        self.log.info(text)
        sql = f"insert into {self.tb_name} " \
            f"values(generate_series(1,{self.value}), 1);"
        pub_thread = ComThread(self.commsh_pub.execut_db_sql,
                               args=(sql,
                                     self.user_param_pub))
        pub_thread.setDaemon(True)
        pub_thread.start()

        text = '--step5:发布端插入数据的同时，订阅端修改发布模式为非二进制模' \
               '式 expect:成功---'
        self.log.info(text)
        sql = f"alter SUBSCRIPTION {self.subname} set (binary=False);"
        sub_thread = ComThread(self.commsh_sub.execut_db_sql,
                               args=(sql,
                                     self.user_param_sub, None,
                                     macro.DB_ENV_PATH_REMOTE1))
        sub_thread.setDaemon(True)
        sub_thread.start()
        sub_thread.join(30)
        result = sub_thread.get_result()
        self.log.info(result)
        self.assertIn(self.constant.alter_sub_succ_msg, result,
                      '执行失败:' + text)
        pub_thread.join(30)
        result = pub_thread.get_result()
        self.log.info(result)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, result,
                      '执行失败:' + text)

        text = '--step6:订阅端查询表数据 expect:同步---'
        self.log.info(text)
        sql = f"select pg_sleep(5.5);select count(*) from {self.tb_name};"
        result = self.commsh_sub.execut_db_sql(sql, self.user_param_sub, None,
                                               macro.DB_ENV_PATH_REMOTE1)
        self.log.info(result)
        self.assertIn(str(self.value), result, '执行失败:' + text)

        text = '--step7:更新发布端数据 expect:成功--'
        self.log.info(text)
        sql = f"update {self.tb_name} set j=999;"
        pub_thread = ComThread(self.commsh_pub.execut_db_sql,
                               args=(sql,
                                     self.user_param_pub))
        pub_thread.setDaemon(True)
        pub_thread.start()

        text = '--step8:发布端插入数据的同时，订阅端修改发布模式为二进制模式 ' \
               'expect:成功---'
        self.log.info(text)
        sql = f"alter SUBSCRIPTION {self.subname} set (binary=True);"
        sub_thread = ComThread(self.commsh_sub.execut_db_sql,
                               args=(sql,
                                     self.user_param_sub, None,
                                     macro.DB_ENV_PATH_REMOTE1))
        sub_thread.setDaemon(True)
        sub_thread.start()
        sub_thread.join(30)
        result = sub_thread.get_result()
        self.log.info(result)
        self.assertIn(self.constant.alter_sub_succ_msg, result,
                      '执行失败:' + text)
        pub_thread.join(30)
        result = pub_thread.get_result()
        self.log.info(result)
        self.assertIn(self.constant.UPDATE_SUCCESS_MSG, result,
                      '执行失败:' + text)

        text = '--step9:订阅端查询表数据 expect:同步---'
        self.log.info(text)
        sql = f"select pg_sleep(5);" \
            f"select count(*) from {self.tb_name} where j =999;"
        result = self.commsh_sub.execut_db_sql(sql, self.user_param_sub, None,
                                               macro.DB_ENV_PATH_REMOTE1)
        self.log.info(result)
        self.assertIn(str(self.value), result, '执行失败:' + text)

    def tearDown(self):
        self.log.info('------------this is tearDown-------------')
        text = '--清理环境--'
        self.log.info(text)
        sql = f"DROP PUBLICATION if exists {self.pubname};"
        drop_pub_result = self.commsh_pub.execut_db_sql(
            sql, sql_type=self.user_param_pub)
        self.log.info(drop_pub_result)
        sql = f"DROP SUBSCRIPTION  {self.subname};"
        drop_sub_result = self.commsh_sub.execut_db_sql(
            sql, self.user_param_sub, None, macro.DB_ENV_PATH_REMOTE1)
        self.log.info(drop_sub_result)
        sql = f"DROP table if exists {self.tb_name} CASCADE;"
        drop_result_sub = self.commsh_sub.execut_db_sql(
                sql, self.user_param_sub, None,
                macro.DB_ENV_PATH_REMOTE1)
        self.log.info(drop_result_sub)
        drop_result_pub = self.commsh_pub.execut_db_sql(
            sql, sql_type=self.user_param_pub)
        self.log.info(drop_result_pub)
        result = self.commsh_pub.execut_db_sql(
        sql, sql_type=self.user_param_pub)
        self.log.info(result)

        guc_res = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host    replication  {self.pri_userdb_sub.db_user} '
            f'{self.pri_userdb_sub.db_host}/32 ')
        self.log.info(guc_res)
        guc_res1 = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host    replication  {self.pri_userdb_pub.db_user} '
            f'{self.pri_userdb_pub.db_host}/32',
            macro.DB_ENV_PATH_REMOTE1)
        self.log.info(guc_res1)
        self.assertTrue(guc_res, '执行失败:' + text)
        self.assertTrue(guc_res1, '执行失败:' + text)
        self.assertIn(self.constant.drop_pub_succ_msg, drop_pub_result,
                      '执行失败' + text)
        self.assertIn(self.constant.drop_sub_succ_msg, drop_sub_result,
                      '执行失败' + text)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, drop_result_pub,
                      '执行失败' + text)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, drop_result_sub,
                      '执行失败' + text)
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
